import React  from 'react';
import {message,Icon,Button,Input,Row,Col,Card,Anchor,Table,Dropdown,Menu,Form,DatePicker,InputNumber,Upload,Select} from 'antd';
import styles from '../style/PropertyDataDetailInfo.scss';
import moment from 'moment';
const Option = Select.Option;
const { RangePicker } = DatePicker;

import {
  ASSET_LEVEL,
  IS_NOT,
  GUARANTEE,
  TRANSPORT_TYPE,
  RETURNED_MONEY_WAY,
  RETURNED_MONEY_SOURCE,
  REMARK_TYPE,
  IS_NOT_MAP
} from 'constants/index';

import api from 'container/api';

//合同
class Constract extends React.Component {

  constructor(props){
    super(props);
    let {id,type} = props;
    this.state ={
      id,
      type,
      data:{},
      isEdit:false
    }
    this.CONSTRACT_TYPE = {
      'UPSTREAM':'上游合同',
      'DOWNSTREAM':'下游合同'
    }
  }

  componentWillMount(){
    this.doFetch();
  }

  async doFetch(){
    let {id,type} = this.state;
    let result = await api('/assets/contract-detail' ,{id,contract_type:type});
    if(!result.success){
      message.error(result.message);
      return
    }
    let data = result.data;
    Object.keys(data).forEach((key,index) => {
      if(key.endsWith('files') && Array.isArray(data[key])){
        data[key].forEach((item,index) => {
          item.uid = this.uuid();
        })
      }
    })
    this.setState({
      data,
      isEdit:false
    })
  }

  toggleEdit (isEdit){
    let {data} = this.state;
    this.setState({isEdit})
  }

  handleSave = () => {
    this.props.form.validateFields((err, values) => {
      if (err) return;
      this.save({...values})
    });
  }

  async save (values) {
    let supplyDate = values.supply_date;
    values.supply_start_date =supplyDate[0]?supplyDate[0].format('YYYY-MM-DD'):null;
    values.supply_end_date = supplyDate[1]?supplyDate[1].format('YYYY-MM-DD'):null;
    values.expire_date = values.expire_date?values.expire_date.format('YYYY-MM-DD'):null;
    values.sign_date = values.sign_date?values.sign_date.format('YYYY-MM-DD'):null;
    delete values.supply_date;
    values.asset_id = this.state.id;
    values.id = this.state.data.id;
    let result = await api("/assets/contract/edit",values);
    if(!result.success){
      message.error(result.message);
      return
    }
    message.success(`更新${this.CONSTRACT_TYPE[this.state.type]}信息成功` , 1 ,() => {
      this.doFetch();
    })
  }

  uuid(){
    return Math.random().toString(36).slice(2);
  }

  render(){
    let {data,type,isEdit} = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <Card 
        title={this.CONSTRACT_TYPE[type]}
        bordered={false} 
        bodyStyle={{backgroundColor:'#fff',padding:'0'}}
        extra={
          this.renderTd(
            <div>
              <Button style={{marginRight:5}} onClick={this.toggleEdit.bind(this,false)}>取消</Button>
              <Button type='primary' onClick={this.handleSave}>保存</Button>
            </div>,
            <a href='javascript:void 0' onClick={this.toggleEdit.bind(this,true)}>
            <Icon type="edit" />
            </a>
          )
        }
      >
        <Form>
        <table className={styles.table}>
          <tbody className='table-form'>
            <tr>
              <th>买方（需方）</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('buyer', {
                      rules: [{required: true, message: '请输入买方' }],
                      initialValue:data.buyer
                    })(
                      <Input  />
                    )}
                  </Form.Item>,
                  `${data.buyer}`
                )}
              </td>
              <th>卖方（供方</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('seller', {
                      rules: [{required: true, message: '请输入卖方' }],
                      initialValue:data.seller
                    })(
                      <Input  />
                    )}
                  </Form.Item>,
                  `${data.seller}`
                )}
              </td>
            </tr>
            <tr>
              <th>合同编号</th>
              <td colSpan={3}>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('number', {
                      rules: [{required: true, message: '请输入卖方' }],
                      initialValue:data.number
                    })(
                      <Input  />
                    )}
                  </Form.Item>,
                  `${data.number}`
                )}
              </td>
            </tr>
            <tr>
              <th>货物品种</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('goods_type', {
                      rules: [{required: true, message: '请输入货物品种' }],
                      initialValue:data.goods_type
                    })(
                      <Input  />
                    )}
                  </Form.Item>,
                  `${data.goods_type}`
                )}
              </td>
              <th>运输方式</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('transport_type', {
                      rules: [{required: true, message: '请选择运输方式' }],
                      initialValue:data.transport_type
                    })(
                      <Select>
                        {Object.keys(TRANSPORT_TYPE).map((key,index) => {
                          return (<Option value={key} key={index}>{TRANSPORT_TYPE[key]}</Option>)
                        })}
                      </Select>
                    )}
                  </Form.Item>,
                  TRANSPORT_TYPE[data.transport_type]
                )}
              </td>
            </tr>
            <tr>
              <th>合同吨数</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('amount', {
                      rules: [{required: false, message: '请输入合同吨数' }],
                      initialValue:data.amount
                    })(
                      <Input addonAfter='吨' />
                    )}
                  </Form.Item>,
                  `${data.amount}吨`
                )}
              </td>
              <th>合同单价</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('unit_price', {
                      rules: [{required: false, message: '请输入合同单价' }],
                      initialValue:data.unit_price
                    })(
                      <Input addonAfter='元/吨' />
                    )}
                  </Form.Item>,
                  `${data.unit_price}元/吨`
                )}
              </td>
            </tr>
            <tr>
              <th>合同金额</th>
              <td>
                {data.total_price}元
              </td>
              <th>供货期间</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('supply_date', {
                      rules: [{ type: 'array',required: true, message: '请选择供货期间' }],
                      initialValue:[
                        data.supply_start_date?moment(data.supply_start_date):null,
                        data.supply_end_date?moment(data.supply_end_date):null
                      ]
                    })(
                      <RangePicker />
                    )}
                  </Form.Item>,
                  `${data.supply_start_date} 至 ${data.supply_end_date}`
                )}
              </td>
            </tr>
            <tr>
              <th>合同签约日</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('sign_date', {
                      rules: [{required: true, message: '请选择合同签约日' }],
                      initialValue:data.sign_date?moment(data.sign_date):null
                    })(
                      <DatePicker />
                    )}
                  </Form.Item>,
                  data.sign_date
                )}
              </td>
              <th>合同到期日</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('expire_date', {
                      rules: [{required: false, message: '请选择合同签约日' }],
                      initialValue:data.expire_date?moment(data.expire_date):null
                    })(
                      <DatePicker />
                    )}
                  </Form.Item>,
                  data.expire_date
                )}
              </td>
            </tr>
            <tr>
              <th>合同影印件</th>
              <td colSpan={3}>
                <Form.Item>
                  {getFieldDecorator('files', {
                    rules: [{ required: false, message: '请上传合同影印件' }],
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                    initialValue:data.files
                  })(
                    <Upload {...this.uploadProps(12,'files')}>
                      {!isEdit?null
                        :<Button>
                          <Icon type="upload" /> 点击上传
                        </Button>
                      } 
                    </Upload>
                  )}
                </Form.Item>
              </td>
            </tr>
            <tr>
              <th>是否委托运输</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('consigned', {
                      rules: [{required: true, message: '请选择是否委托运输' }],
                      initialValue:data.consigned==true?'1':'0'
                    })(
                      <Select>
                        {Object.keys(IS_NOT_MAP).map((key,index) => {
                          return (<Option key={index} value={key} >{IS_NOT_MAP[key]}</Option>)
                        })}
                      </Select>
                    )}
                  </Form.Item>,
                  `${IS_NOT(data.consigned)}`
                )}
              </td>
              <th>委托运输人</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('consignee', {
                      rules: [{required: false, message: '请输入委托运输人' }],
                      initialValue:data.consignee
                    })(
                      <Input placeholder='请输入委托运输人'/>
                    )}
                  </Form.Item>,
                  `${data.consignee}`
                )}
              </td>
            </tr>
            <tr>
              <th>委托运输协议</th>
              <td colSpan={3}>
                <Form.Item>
                  {getFieldDecorator('consigned_files', {
                    rules: [{ required: false, message: '请上传委托运输协议' }],
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                    initialValue:data.consigned_files
                  })(
                    <Upload {...this.uploadProps(13,'consigned_files')}>
                      {!isEdit?null
                        :<Button>
                          <Icon type="upload" /> 点击上传
                        </Button>
                      } 
                    </Upload>
                  )}
                </Form.Item>
              </td>
            </tr>
            <tr>
              <th>是否委托收货</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('delivered', {
                      rules: [{required: true, message: '请选择是否委托收货' }],
                      initialValue:data.delivered==true?'1':'0'
                    })(
                      <Select>
                        {Object.keys(IS_NOT_MAP).map((key,index) => {
                          return (<Option key={index} value={key} >{IS_NOT_MAP[key]}</Option>)
                        })}
                      </Select>
                    )}
                  </Form.Item>,
                  `${IS_NOT(data.delivered)}`
                )}
              </td>
              <th>委托收货人</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('deliverer', {
                      rules: [{required: false, message: '请输入委托收货人' }],
                      initialValue:data.deliverer
                    })(
                      <Input placeholder='请输入委托收货人'/>
                    )}
                  </Form.Item>,
                  `${data.deliverer}`
                )}
              </td>
            </tr>
            <tr>
              <th>委托收货协议</th>
              <td colSpan={3}>
                <Form.Item>
                  {getFieldDecorator('delivered_files', {
                    rules: [{ required: false, message: '请上传委托收货协议' }],
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                    initialValue:data.delivered_files
                  })(
                    <Upload {...this.uploadProps(14,'delivered_files')}>
                      {!isEdit?null
                        :<Button>
                          <Icon type="upload" /> 点击上传
                        </Button>
                      } 
                    </Upload>
                  )}
                </Form.Item>
              </td>
            </tr>
            <tr>
              <th>是否委托结算</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('reckoned', {
                      rules: [{required: true, message: '请选择是否委托结算' }],
                      initialValue:data.reckoned==true?'1':'0'
                    })(
                      <Select>
                        {Object.keys(IS_NOT_MAP).map((key,index) => {
                          return (<Option key={index} value={key} >{IS_NOT_MAP[key]}</Option>)
                        })}
                      </Select>
                    )}
                  </Form.Item>,
                  `${IS_NOT(data.reckoned)}`
                )}
              </td>
              <th>委托结算人</th>
              <td>
                {this.renderTd(
                  <Form.Item>
                    {getFieldDecorator('reckoner', {
                      rules: [{required: false, message: '请输入委托结算人' }],
                      initialValue:data.reckoner
                    })(
                      <Input placeholder='请输入委托结算人'/>
                    )}
                  </Form.Item>,
                  `${data.reckoner}`
                )}
              </td>
            </tr>
            <tr>
              <th>委托结算协议</th>
              <td colSpan={3}>
                <Form.Item>
                  {getFieldDecorator('reckoned_files', {
                    rules: [{ required: false, message: '请上传委托结算协议' }],
                    valuePropName: 'fileList',
                    getValueFromEvent: this.normFile,
                    initialValue:data.reckoned_files
                  })(
                    <Upload {...this.uploadProps(15,'reckoned_files')}>
                      {!isEdit?null
                        :<Button>
                          <Icon type="upload" /> 点击上传
                        </Button>
                      } 
                    </Upload>
                  )}
                </Form.Item>
              </td>
            </tr>
          </tbody>
        </table>
        </Form>
      </Card>
    )
  }


  uploadProps = (file_type,field) => {
    let _this = this;
    let {data} = this.state;
    data[field] = data[field] || [];
    return {
      customRequest:async ({ file, fileList }) => {
        let {defaultFileList=[]} = this.state;
        let result = await api.upload(`/file/upload?file_type=${file_type}`,file);
        if(result){
          let uid = this.uuid();
          data[field].push({
            name:file.name,
            url:result.data.url,
            type:result.data.type,
            uid:uid,
            status:'done'
          })
        }
        this.props.form.setFieldsValue({
          [field]:data[field]
        })
        this.setState({data})
      },
      onRemove:(file) => {
        let {isEdit} = _this.state;
        return isEdit
      }
    }
  }

  normFile = (e) => {
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  }

  renderTd (editHtml,html) {
    let {isEdit} = this.state;
    if(isEdit) return editHtml;
    return html;
  }
}
export default Form.create()(Constract);
